package com.hankol.community.fragment

import android.annotation.SuppressLint
import android.view.MotionEvent
import androidx.lifecycle.Observer
import androidx.viewpager2.widget.ViewPager2
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.bean.VideoReadBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.HKLogUtils
import com.baselibrary.utils.SpUtils
import com.baselibrary.utils.StatusBarUtil
import com.baselibrary.activity.BaseLazyFragment
import com.hankol.community.R
import com.hankol.community.adapter.VideoPageAdapter
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.databinding.FragmentCommunityVideoBinding
import com.hankol.community.viewmodel.VideoPageViewModel
import com.scwang.smartrefresh.layout.constant.RefreshState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**首页-视频页
 * @time: 2022/3/24 10:05
 * @description:
 */
class CommunityVideoFragment : BaseLazyFragment(true) {
    private lateinit var mDataBinding: FragmentCommunityVideoBinding
    private lateinit var mViewModel: VideoPageViewModel
    private lateinit var mAdapter: VideoPageAdapter
    private var pageNum = "0"
    val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)
    private var mCurrentItem = 0
    var mList = mutableListOf<VideoReadBean.DataBeanX.DataBean>()

    companion object {
        fun newInstance(): CommunityVideoFragment {
            return CommunityVideoFragment()
        }
    }

    override fun init() {
        mViewModel = getFragmentViewModelProvider(this).get(VideoPageViewModel::class.java)
        mDataBinding = getDataBinding<FragmentCommunityVideoBinding>()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initView()
        addObserver()
        initListener()
        SensorsDataManager.instance.communityVideoView()
    }

    override fun lazyLoadData() {
        mViewModel.reqVideoPageList(requireActivity(), pageNum)
    }

    fun doRefresh() {
        mDataBinding.vpVideoDetails.setCurrentItem(0, false)
        mDataBinding.smartRefresh.autoRefresh()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_community_video
    }

    private fun initListener() {
        mDataBinding.smartRefresh.setOnRefreshListener {
            if(mList.size>0) {
                EventBusUtils.sendNotify(MessageBus.msgId_video_page_refresh)
                mViewModel.reqVideoHistoryAdd(mList[0].id.toLong())
                mAdapter.fragments.clear()
                mAdapter.notifyDataSetChanged()
            }
            pageNum = "0"
            mList.clear()
            mViewModel.reqVideoPageList(requireActivity(), pageNum)
        }
    }


    private fun initView() {
        mDataBinding.smartRefresh.setEnableLoadMore(false)
        mAdapter = VideoPageAdapter(requireActivity())
        mDataBinding.vpVideoDetails.adapter = mAdapter
        SensorsDataManager.instance.onCreateTime()
        SensorsDataManager.instance.setFormPagePos("视频")
        mDataBinding.vpVideoDetails.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                if (mList.size > 0) {
                    SpUtils.putString(requireContext(), Constants.KEY_CURRENT_PLAYING_VIDEO_ID, "${mList[position].id}")
                }
                mCurrentItem = position
                if (mCurrentItem == mList.size - 1) {
                    //"加载中，请稍后".toast()
                    //获取推荐列表
                    mViewModel.reqVideoPageList(requireActivity(), pageNum)
                }
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                if(mDataBinding.smartRefresh.state==RefreshState.None) {
                    EventBusUtils.sendNotify2Value(MessageBus.msgId_video_page_switch_offset, positionOffset,"${mList[position].id}")
                }
            }
        })
    }

    private fun addObserver() {
        mViewModel.videoDetailsLD.observe(this, Observer {
            mDataBinding.smartRefresh.finishRefresh()
            if (it != null) {
                pageNum = it.nextCursor
                val list: ArrayList<VideoReadBean.DataBeanX.DataBean> = it.data
                mList.addAll(list)
                mAdapter.setDataList(mList)
                mAdapter.notifyDataSetChanged()
            }
        })
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
    }

    //切换顶部 发现、视频 回调
    @SuppressLint("SuspiciousIndentation")
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        val isPause = !isVisibleToUser
        if (attachActivity.checkNotNull()) {
            SpUtils.putBoolean(requireContext(), Constants.KEY_CURRENT_IS_VIDEO_PAGE, isVisibleToUser)
            //通知暂停视频播放
            val videoId = SpUtils.getString(requireContext(), Constants.KEY_CURRENT_PLAYING_VIDEO_ID)
            if (videoId.checkNotNull()) {
                EventBusUtils.sendNotify2Value(MessageBus.msgId_video_page_pause_video_play, isPause, videoId)
            }
            StatusBarUtil.setStatusBarDarkTheme(attachActivity, isPause)
            EventBusUtils.sendNotify1Value(MessageBus.msgId_current_playing_video_page, isVisibleToUser)
        }
    }

    /*    override fun onResume() {
            super.onResume()
            if (attachActivity.checkNotNull()) {
                //通知 视频播放
                val videoId = SpUtils.getString(requireContext(), Constants.KEY_CURRENT_PLAYING_VIDEO_ID)
                if (videoId.checkNotNull()) {
                    EventBusUtils.sendNotify2Value(MessageBus.msgId_video_page_pause_video_play, false, videoId)
                }
            }
        }

        override fun onPause() {
            super.onPause()
            if (attachActivity.checkNotNull()) {
                //通知暂停视频播放
                val videoId = SpUtils.getString(requireContext(), Constants.KEY_CURRENT_PLAYING_VIDEO_ID)
                if (videoId.checkNotNull()) {
                    EventBusUtils.sendNotify2Value(MessageBus.msgId_video_page_pause_video_play, true, videoId)
                }
            }
        }*/
    override fun onDestroyView() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        SpUtils.putBoolean(requireContext(),Constants.KEY_CURRENT_IS_VIDEO_PAGE,false)
        super.onDestroyView()
    }
}